const util = require('../../utils/util.js');
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '',
    scan: [],
    index: -1,
    status: false,
    title: '',
    skip: 0,
    time:''
  },

  //搜索
  search: function (e) {
    this.setData({
      title: e.detail.value,
      skip: 0
    })
    this.getScan()
  },

  //云函数获取scan集合数据
  getScan: function (callback) {
    if (!callback) {
      callback = res => { }
    }
    wx.showLoading({
      title: '数据加载中',
    })
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getScan',
      // 传给云函数的参数
      data: {
        title: this.data.title,
        skip: this.data.skip
      }
    }).then(res => {
      let skip = this.data.skip;
      let scan = this.data.scan;
      let data = res.result.data;

      for (let i = 0; i < data.length; i++) {
        data[i].createTime = util.formatTime(new Date(data[i].create_time))
      }

      this.setData({
        scan: skip == 0 ? data : scan.concat(data)
      }, res => {
        wx.hideLoading()
        callback();
      }
      )
      this.setData({
        skip: skip + 20
      })

    }).catch(console.error)
  },

  //文本框修改事件
  textareaAInput(e) {
    this.setData({
      content: e.detail.value
    })
  },

  //复制
  getcontent: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success(res) {
        wx.getClipboardData({
          success(res) {
          }
        })
      }
    })
  },

  //删除
  delete: function (e) {
    let that = this;
    let data = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确定删除吗?',
      success(res) {
        if (res.confirm) {
          db.collection('scan').doc(data.id).remove()
            .then(res => {
              that.setData({
                skip: 0
              })
              that.getScan()
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              })
            })
            .catch(console.error)
        }
      }
    })
  },

  //获取当前编辑数据索引
  getIndex: function (e) {
    let scan = this.data.scan;
    if (this.data.index > -1) {
      scan[this.data.index]['status'] = 0;
    }
    let index = e.currentTarget.dataset.id
    scan[index]['status'] = 1;
    this.setData({
      scan,
      index
    })
  },

  //切换到修改文本框
  editScan: function (e) {
    let scan = this.data.scan;
    scan[this.data.index]['content'] = e.detail.value;
    this.setData({
      scan
    })
  },

  //保存修改的数据
  saveScan: function (e) {
    let content = this.data.scan[this.data.index]['content'];
    db.collection('scan').doc(e.currentTarget.dataset.id).update({
      data: {
        content
      }
    }).then(res => {
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
      let scan = this.data.scan;
      if (this.data.index > -1) {
        scan[this.data.index]['status'] = 0;
      }
      this.setData({
        scan
      })
    })
  },

  //生成笔记并跳转
  addnote:function(){
    db.collection('note').add({
      data: {
        title:'',
        text: this.data.content,
        type: 2,
        create_time: new Date()
      }
    }).then(res => {
      wx.navigateTo({
        url: '../voice/voice?id='+res._id
      })
    }).catch(console.error)
  },

  //添加扫描处理后的数据
  addscan: function () {
    db.collection('scan').add({
      data: {
        content: this.data.content,
        status: 0,
        create_time: new Date()
      }
    }).then(res => {
      
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    }).catch(console.error)
  },

  //调用云函数，识别图片文字
  uploadImage() {
    var myThis = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(chooseImage_res) {
        wx.getFileSystemManager().readFile({
          filePath: chooseImage_res.tempFilePaths[0], //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success(base64_res) {
            wx.showLoading({
              title: '识别中……',
              mask: false,
            })
            wx.cloud.callFunction({
              name: 'OCR_Detection',
              data: {
                base64: base64_res.data
              }
            }).then(res => {
              if (res.result.TextDetections.length == 0) {
                wx.hideLoading()
                wx.showModal({
                  title: '提示',
                  content: '未检测到文字，请重试',
                  success() {
                  }
                })
              } else {
                var data = "";
                for (let i = 0; i < res.result.TextDetections.length; i++) {
                  data = data + res.result.TextDetections[i].DetectedText + "\n\n"
                }
                myThis.setData({
                  content: data,
                  status: true,
                  time:util.formatTime(new Date())
                })
                wx.hideLoading()
                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 200
                })
              }
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getScan()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      skip: 0
    })
    this.getScan(res => {
      wx.stopPullDownRefresh();
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getScan()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})